<?php

require_once __DIR__ . '/includes/init.php';

if (isset($_SESSION['authenticated']) || isset($_SESSION['parsclick_auth'])) {
	echo "<script>top.window.location = 'mainpage.php'</script>";
}

use sessions\AutoLogin;

	$interval = 5;

	function checkLogin($user_key) {

		global $interval;

		require __DIR__ . '/db_bb_connect.php';		

		$sql = "SELECT attempts, (CASE when lastlogin is not NULL and DATE_ADD(LastLogin, INTERVAL $interval MINUTE)>NOW() then 1 else 0 end) AS Denied FROM loginattempts WHERE user_key = '$user_key'";
  		
  		$result = $db->query($sql);
  		$data = $result->fetch_assoc();

  		//Verify that at least one login attempt is in database

		if (!$data) {
			return 0;
		}

		if ($data["attempts"] >= 5){
			
			if($data["Denied"] == 1){
				return 1;
			} else { 
				clearLoginAttempts($user_key);
				return 0; 
			}
		} else {
			return 0;
		}
		return 0;
	}

	function addLoginAttempt($user_key) {

		global $interval;

		$user_ip = $_SERVER['REMOTE_ADDR'];

		require __DIR__ . '/db_bb_connect.php';

  	    //Increase number of attempts. Set last login attempt if required.

		$sql = "SELECT lastlogin FROM loginattempts WHERE user_key = '$user_key'";
  		$result = $db->query($sql);
  		$data = $result->fetch_assoc();

  		$datelastlogin = $data["lastlogin"];

  		if ( date("Y-m-d H:i:s") > date('Y-m-d H:i:s', strtotime("$datelastlogin + $interval minutes"))) {
  			clearLoginAttempts($user_key);
  		}

  		$sql = "SELECT * FROM loginattempts WHERE user_key = '$user_key'";
  		$result = $db->query($sql);
  		$data = $result->fetch_assoc();

		if($data){
			$attempts = $data["attempts"] + 1;    

			if($attempts == 3) {
				$sql = "UPDATE loginattempts SET attempts=$attempts, lastlogin=NOW() WHERE user_key = '$user_key'";
				$db->query($sql); 

			} else {
				$sql = "UPDATE loginattempts SET attempts=$attempts, lastlogin=NOW() WHERE user_key = '$user_key'";
				  $db->query($sql);
			}

		} else {
			$sql = "INSERT INTO loginattempts (user_key,attempts,ip,lastlogin) values ('$user_key',1, '$user_ip', NOW())";
			$db->query($sql);
		}
	}

	function clearLoginAttempts($user_key) {

			require __DIR__ . '/db_bb_connect.php';

			$sql = "UPDATE loginattempts SET attempts = 0 WHERE user_key = '$user_key'";
			return $db->query($sql);
	}

if (isset($_POST['login'])) {

	$username = trim($_POST['username']);
	$pwd = trim($_POST['pwd']);
	$sql = "SELECT pwd FROM users WHERE username = :username";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':username',$username);
	$stmt->execute();
	$storedpw = $stmt->fetchColumn();

	$sql = "SELECT allowed FROM users WHERE username = :username";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':username',$username);
	$stmt->execute();
	$allowed = $stmt->fetchColumn();

	$sql = "SELECT user_key FROM users WHERE username = :username";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':username',$username);
	$stmt->execute();
	$user_key = $stmt->fetchColumn();

	$sql = "SELECT type FROM users WHERE username = :username";
	$stmt = $db->prepare($sql);
	$stmt->bindParam(':username',$username);
	$stmt->execute();
	$type = $stmt->fetchColumn();

	addLoginAttempt($user_key);

	if (checkLogin($user_key) == 1){
		$error = "Login of user $username is denied for $interval minutes.";
	} else {

	if ( password_verify($pwd,$storedpw) && $allowed == 1 && $type == 'Coach' ) {

		$sql = "SELECT user_key FROM users WHERE username = :username";
		$stmt = $db->prepare($sql);
		$stmt->bindParam(':username',$username);
		$stmt->execute();
		$user_key = $stmt->fetchColumn();

		session_regenerate_id(true);		
		$_SESSION['username'] = $username;
		$_SESSION['authenticated'] = true;
		$_SESSION['user_key'] = $user_key;

		if ($user_key != '23cc68eb'){

			$browser = $_SERVER['HTTP_USER_AGENT'];
			$ip = $_SERVER['REMOTE_ADDR'];

			$sql = "INSERT INTO devices (user_key, device, IP) VALUES ('$user_key','$browser','$ip')";
			$stmt = $db->prepare($sql);
			$stmt->bindParam(':username',$username);
			$stmt->execute();
		}


		if (isset($_POST['remember'])) {
			$autologin = new AutoLogin($db);
			$autologin->persistentLogin();
		}

		header('Location: mainpage.php');
		exit;

	} else if ($type == 'Player') {

		if (checkLogin($user_key) == 0) {
			$error = "Login failed. Only Coaches Allowed.";
		}

	} else { 
			if (checkLogin($user_key) == 0) {
				$error = "Login failed. Check username and password.";
			}
	}

	
		}
	}

?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
  <meta charset="utf-8">
	<title>Login Basketbal</title>

	<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
 <link rel="icon" href="./images/basketball2.png" type="image/png"> 

<style type="text/css">

#loginwell{
		background: white;
		border-radius: 10px;
		opacity : 0.9;
		padding:20px;
		max-width:400px;

}


#maindiv:after {
    content : "";
    display: block;
    position: absolute;
    top: 0;
    left: 0;
    background-image: url('./images/bb01.jpg'); 
    width: 100%;
    height: 100%;
    opacity : 0.7;
    z-index: -1;
    background-repeat: repeat;
}



 #pwd + .glyphicon {
   cursor: pointer;
   pointer-events: all;
 }

 #showpassword{
	opacity : 0.5;
 	filter: alpha(opacity=50); /* For IE8 and earlier */
 }

 #showpassword:hover{
 	opacity : 1.0;
 	filter: alpha(opacity=100); /* For IE8 and earlier */
 }

.btn-warning{
 	background: darkorange;
 }


</style>



</head>
<body>
<br><br><br>

<div class="container-fluid" id="maindiv">
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">

<Br><Br><br>
<Br><Br><br>
<center>
<div id="loginwell">

<br><br><br>

<?php
if (isset($error)) {
	echo "<p>$error</p>";
}

if (isset($message)) {
	echo "<p>$message</p>";
}

?>

<form action="<?= $_SERVER['PHP_SELF'];?>" method="post" class="form-horizontal">
	<div class="input-group">
		<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>	
			<input type="text" name="username" id="username" class="form-control" placeholder="Username" autofocus>
	</div>
	<br/>

	<div class="input-group">
		<span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
			<input type="password" name="pwd" id="pwd" class="form-control" placeholder="Password">
			<i class="glyphicon glyphicon-eye-open form-control-feedback" id="showpassword"></i>
	</div>

	
	<div class="form-group">
		<div class="col-sm-offset-2 col-sm-6">
			<div class="checkbox">
				<label for="remember"> 
					<input type="checkbox" name="remember" id="remember" checked> Remember me
				</label>
			</div>
		</div>
	</div> 

<br/>
	
	<div class="form-group">
		<div>
			<button id="loginbutton" type="submit" name="login" id="login" class="btn btn-warning btn-block"> <strong>Log In</strong>  </button>
		</div>
	</div>
</form>

</div>

</center>

</div>


<div class="col-sm-3"></div>

</div>
</div>


</body>


<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<script type="text/javascript">

$('#pwd + .glyphicon').on('click', function() {
	$(this).toggleClass('glyphicon-eye-close').toggleClass('glyphicon-eye-open');
    var x = document.getElementById("pwd");
    if (x.type === "password") {
        x.type = "text";
    } else {
        x.type = "password";
    }
});


</script>


</html>